package com.onlyxiahui.wofa.client.net.core.connect.mina;

import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * Description <br>
 * Date 2021-04-11 13:06:30<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */
public class DataCodecDecoder extends CumulativeProtocolDecoder {

	protected static final Logger logger = LoggerFactory.getLogger(DataCodecDecoder.class);
	// 字符编码类型
	private Charset charset = Charset.forName("UTF-8");

	public DataCodecDecoder() {
	}

	public DataCodecDecoder(Charset charset) {
		if (null != charset) {
			this.charset = charset;
		}
	}

	@Override
	protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
		try {
			if (in.prefixedDataAvailable(4, Integer.MAX_VALUE)) {
				// 标记当前位置，以便reset
				in.mark();
				int size = in.getInt();

				// 如果消息内容不够，则重置，相当于不读取size
				if ((size) > in.remaining()) {
					in.reset();
					// 接收新数据，以拼凑成完整数据
					return false;
				}
				byte[] bodyByte = new byte[size];
				in.get(bodyByte, 0, size);
				String text = new String(bodyByte, charset);
				out.write(text);
				// 接收新数据，以拼凑成完整数据
				return true;
			}
		} catch (Exception e) {
			in.sweep();
			logger.error("", e);
		}
		return false;
	}
}
